"use strict";

var C = require('../common');

function createMiddleware(owner, mount, name, cfg, cb) {
    var factory = owner.loadExtension('middlewares', name);
    owner.console('Creating middleware [' + name + '] @ "' + mount + '" ...');
    factory(owner, mount, cfg, function (err, middleware) {
        if (err) return cb(err);

        owner.console('Middleware [' + name + '] is created.');
        cb(null, middleware);
    });
}

module.exports = {

    type: 'prepare',

    createMiddleware: createMiddleware,

    load: function (owner, middlewares, cb) {
        owner.middlewares || (owner.middlewares = []);

        C.async.eachSeries(C._.keys(middlewares), function (name, cb2) {
            createMiddleware(owner, owner.route, name, middlewares[name], function (err, middleware) {
                if (err) return cb2(err);

                owner.middlewares.push(middleware);
                cb2();
            });
        }, cb);
    }
};

/**
 * Middleware factory callback
 *
 * @callback middlewareFactory
 * @param {Error} err - Error object
 * @param {middleware} middleware - Created middleware
 */